package com.example.shangguigu.digest;



import sun.misc.BASE64Encoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @DESCRIPTION: 消息摘要算法学习：SM3 SHA1 SHA256 SHA512 MD5
 * @USER: shg
 * @DATE: 2023/2/25 12:38
 */
public class DigestDemo {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        StringToHex("sunhongguang");

        System.out.println("md5消息摘要："+Test1("aa", "MD5"));
        System.out.println("SHA-1消息摘要："+Test1("aa", "SHA-1"));
        System.out.println("SHA-256消息摘要："+Test1("aa", "SHA-256"));
        System.out.println("SHA-512消息摘要："+Test1("aa", "SHA-512"));

    }

    private static void StringToHex(String aa) {
        byte[] bytes = aa.getBytes();
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            String string = Integer.toHexString(aByte);
            sb.append(string);
        }
        System.out.println(sb);
    }

    private static String Test1(String data,String algorithm) throws NoSuchAlgorithmException {

        MessageDigest digest = MessageDigest.getInstance(algorithm);
        byte[] digestResult = digest.digest(data.getBytes());

        String result = stringToHex(digestResult);
        return result;
    }

    // 把通过MD5加密的消息摘要的字节数组转换成16进制字符串
    private static String stringToHex(byte[] digestResult) {
        StringBuilder sb = new StringBuilder();
        for (byte b : digestResult) {
            // 转成 16进制

            String s = Integer.toHexString(b & 0xff);
            // System.out.println(s);
            if (s.length() == 1){
                // 如果生成的字符只有一个，前面补0
                s = "0"+s;
            }
            sb.append(s);
        }
        return sb.toString();
    }
}
